document.addEventListener('DOMContentLoaded', function() {
    const terminal = document.getElementById('terminal');
    const commandInput = document.getElementById('commandInput');

    commandInput.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
            const command = commandInput.value.trim();
            if (command) {
                executeCommand(command);
            }
            commandInput.value = '';
        }
    });

    function executeCommand(command) {
        fetch('/execute', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'command=' + encodeURIComponent(command)
        })
            .then(response => response.json())
            .then(data => {
                // The response will be handled by the page refresh
                window.location.reload();
            })
            .catch(error => console.error('Error:', error));
    }

    // Auto-scroll to bottom
    terminal.scrollTop = terminal.scrollHeight;

    // Focus input on any click in terminal
    terminal.addEventListener('click', function() {
        commandInput.focus();
    });
});